package com.qianfeng.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.ssm.cache.SceneCache;
import com.qianfeng.ssm.event.AnyEvent;
import com.qianfeng.ssm.exceptions.MyBaseException;
import com.qianfeng.ssm.mapper.PersonMapper;
import com.qianfeng.ssm.pojo.Person;
import com.qianfeng.ssm.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.qianfeng.ssm.utils.ResultCode;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zhao_Win
 * @version V1.0
 * @Project AllDay
 * @Date 2022/3/10 16:02
 */
@Service
@Transactional
public class PersonServiceImpl implements PersonService {

    private PersonMapper PersonMapper;

    private SceneCache sceneCache;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context){
        this.context = context;
    }

    @Autowired
    public void setPersonMapper(PersonMapper PersonMapper){
        this.PersonMapper = PersonMapper;
    }
    @Autowired
    public void setSceneCache(SceneCache sceneCache){
        this.sceneCache = sceneCache;
    }


    @Override
    public Person findById(Long id) {
        return PersonMapper.findById(id);
    }

    @Override
    public PageInfo<Person> findAll(int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
//        List<Person> Persons = PersonMapper.findAll();
//        PageInfo<Person> PersonPageInfo = new PageInfo<>(Persons);
        List<Person> allPerson = sceneCache.getAllPerson();
        List<Person> collect = allPerson.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<Person> pageInfo = new PageInfo<>(collect);
        pageInfo.setTotal(allPerson.size());

        context.publishEvent(new AnyEvent());
        return pageInfo;

    }

    @Override
    public int addPerson(Person boy) {
        Assert.isTrue(!boy.isEmpty(), ()->{
            throw new MyBaseException("no data!>>>>>>>>>>>>", ResultCode.DATA_EMPTY);
        });
        return PersonMapper.addPerson(boy);

    }

    @Override
    public int deletePerson(Long id) {
        System.err.println("删除结果："+id);
        return PersonMapper.deletePerson(id);
    }

    @Override
    public int updatePersonById(Person Person) {
        Assert.isTrue(!Person.isEmpty(), ()->{
            throw new MyBaseException("数据空", ResultCode.DATA_EMPTY);
        });
        return PersonMapper.addPerson(Person);
    }
}
